<template>

  <view class="container">
    <u-navbar
        title="事件申报"
        :autoBack="false"
        bgColor="transparent"
        leftIcon=""
        :safeAreaInsetTop="true"
        rightIconColor="#FFFFFF"
        titleStyle="color:#FFFFFF; font-size: 32rpx; font-weight: 600;"
    >
    </u-navbar>
    <view  class="content">
      <view>
        <u--form
            labelPosition="left"
            labelWidth="50"
            :model="model"
            :rules="rules"
            ref="uForm"
        >
          <u-form-item
              label="类型"
              prop="info.type"
              borderBottom
              @click="showType = true; hideKeyboard()"
          >
            <u--input
                v-model="model.info.typeName"
                disabled
                :customStyle="{backgroundColor:'#ffffff'}"
                placeholder="请选择事件类型"
            ></u--input>
            <u-icon
                slot="right"
                name="arrow-right"
            ></u-icon>
          </u-form-item>
          <u-form-item
              label="主题"
              prop="info.title"
              borderBottom
          >
            <u--input
                v-model="model.info.title"
                :customStyle="{backgroundColor:'#ffffff'}"
                placeholder="请输入事件主题"
            ></u--input>
          </u-form-item>
          <u-form-item
              label="描述"
              prop="info.description"
              borderBottom
          >
            <u--textarea v-model="model.info.description" placeholder="请输入事件描述"></u--textarea>
          </u-form-item>
          <u-form-item
              label="备注"
              prop="info.remark"
              borderBottom
          >
            <u--textarea v-model="model.info.remark" placeholder="请输入备注"></u--textarea>
          </u-form-item>
          <u-form-item
              label="照片"
              prop="info.photo"
              borderBottom
          >
            <u-upload
                :fileList="list"
                @afterRead="afterRead"
                @delete="deletePic"
                :customStyle="{backgroundColor:'#ffffff',padding:'20rpx',border:'1rpx solid #dddddd',borderRadius:'8rpx'}"
                multiple
                :previewFullImage="true"
                :maxCount="4"
            ></u-upload>
          </u-form-item>

        </u--form>
        <u-action-sheet
            :show="showType"
            :actions="actions"
            title="请选择事件类型"
            @close="showType = false"
            @select="typeSelect"
        >
        </u-action-sheet>
      </view>
      <u-button @click="submit" class="submit">提交</u-button>
      <u-toast ref="uToast"></u-toast>
    </view>
  </view>
</template>

<script>

import Tabbar from "../../tabbar.vue";
import config from "../../../../config.js";
import {getToken} from "../../../../util/auth";
import {nextFlowNodeByStart, startFlow} from '@/api/exam/apply'

export default {
  components: {Tabbar},
  data() {
    return {
      list: [],// 所有的次数
      showType: false,
      model: {
        info: {
          type: '',
          title: '',
          description: '',
          photo: '',
          remark: '',
        },
      },
      actions: [
        {
          id: 1,
          name: '公共设施损坏',
        },
        {
          id: 2,
          name: '环境卫生问题',
        },
        {
          id: 3,
          name: '邻里纠纷',
        },
        {
          id: 4,
          name: '安全问题',
        },
        {
          id: 5,
          name: '交通问题',
        },
        {
          id: 6,
          name: '宠物管理',
        },
        {
          id: 7,
          name: '建筑施工问题',
        },
        {
          id: 8,
          name: '环境问题',
        },
        {
          id: 9,
          name: '公共服务问题',
        },
        {
          id: 10,
          name: '其他问题',
        },
      ],
      rules: {
        'info.type': {
          type: 'integer',
          required: true,
          message: '请选择事件类型',
          trigger: ['blur', 'change']
        },
        'info.title': {
          type: 'string',
          required: true,
          message: '请输入事件主题',
          trigger: ['blur', 'change']
        },
        'info.description': {
          type: 'string',
          required: true,
          message: '请输入事件描述',
          trigger: ['blur', 'change']
        },
      },
    }
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules)

  },
  methods: {
    // 删除图片
    deletePic(event) {
      this.list.splice(event.index, 1)
    },
    typeSelect(e) {
      this.model.info.type = e.id
      this.model.info.typeName = e.name
      this.$refs.uForm.validateField('info.type')
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this.list.length
      lists.map((item) => {
        this.list.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this.list[fileListLen]
        this.list.splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    showToast(params, fun) {
      this.$refs.uToast.show({
        ...params,
        complete() {
          fun()
        }
      })
    },
    submit() {
      this.$refs.uForm.validate().then(res => {
        let lists = []
        for (let i = 0; i < this.list.length; i++) {
          let listElement = this.list[i];
          lists.push({
            name: listElement.name,
            url: listElement.url,
          })
        }
        // 流程ID
        let deploymentId = "65132"
        let procDefId = "flow_p1wxq7ft:54:65135"
        let data = {
          "deploymentId": deploymentId,
          "variables": {
            "type": this.model.info.type,
            "title": this.model.info.title,
            "description": this.model.info.description,
            "photo": JSON.stringify(lists),
            "remark": this.model.info.remark
          }
        }
        nextFlowNodeByStart(data).then(res => {
          if (res.code === 200) {
            let variables = {
              "type": this.model.info.type,
              "title": this.model.info.title,
              "description": this.model.info.description,
              "photo": JSON.stringify(lists),
              "remark": this.model.info.remark,
              "variables": {
                "formRef": "elForm",
                "formModel": "formData",
                "size": "medium",
                "labelPosition": "right",
                "labelWidth": 100,
                "formRules": "rules",
                "gutter": 15,
                "disabled": true,
                "span": 24,
                "formBtns": false,
                "fields": [{
                  "__config__": {
                    "label": "事件类型",
                    "showLabel": true,
                    "labelWidth": null,
                    "tag": "el-select",
                    "tagIcon": "select",
                    "layout": "colFormItem",
                    "span": 24,
                    "required": true,
                    "regList": [{"required": true, "message": "请选择事件类型事件类型", "trigger": "change"}],
                    "changeTag": true,
                    "document": "https://element.eleme.cn/#/zh-CN/component/select",
                    "formId": 101,
                    "renderKey": "1011717396960711",
                    "defaultValue": this.model.info.type
                  },
                  "__slot__": {"options": [{"label": "选项一", "value": 1}, {"label": "选项二", "value": 2}]},
                  "placeholder": "请选择事件类型事件类型",
                  "style": {"width": "100%"},
                  "clearable": true,
                  "disabled": false,
                  "filterable": false,
                  "multiple": false,
                  "__vModel__": "type"
                }, {
                  "__config__": {
                    "label": "事件主题",
                    "labelWidth": null,
                    "showLabel": true,
                    "changeTag": true,
                    "tag": "el-input",
                    "tagIcon": "input",
                    "required": true,
                    "layout": "colFormItem",
                    "span": 24,
                    "document": "https://element.eleme.cn/#/zh-CN/component/input",
                    "regList": [{"required": true, "message": "请输入事件主题", "trigger": "blur"}],
                    "formId": 102,
                    "renderKey": "1021717396974337",
                    "defaultValue": this.model.info.title
                  },
                  "__slot__": {"prepend": "", "append": ""},
                  "placeholder": "请输入事件主题",
                  "style": {"width": "100%"},
                  "clearable": true,
                  "prefix-icon": "",
                  "suffix-icon": "",
                  "maxlength": null,
                  "show-word-limit": false,
                  "readonly": false,
                  "disabled": false,
                  "__vModel__": "title"
                }, {
                  "__config__": {
                    "label": "问题描述",
                    "labelWidth": null,
                    "showLabel": true,
                    "tag": "el-input",
                    "tagIcon": "textarea",
                    "required": true,
                    "layout": "colFormItem",
                    "span": 24,
                    "regList": [{"required": true, "message": "请输入问题描述", "trigger": "blur"}],
                    "changeTag": true,
                    "document": "https://element.eleme.cn/#/zh-CN/component/input",
                    "formId": 103,
                    "renderKey": "1031717396997020",
                    "defaultValue": this.model.info.description
                  },
                  "type": "textarea",
                  "placeholder": "请输入问题描述",
                  "autosize": {"minRows": 4, "maxRows": 4},
                  "style": {"width": "100%"},
                  "maxlength": null,
                  "show-word-limit": false,
                  "readonly": false,
                  "disabled": false,
                  "__vModel__": "description"
                }, {
                  "__config__": {
                    "label": "拍照上传",
                    "tag": "el-upload",
                    "tagIcon": "upload",
                    "layout": "colFormItem",
                    "defaultValue": "[{\"name\":\"/profile/upload/2024/06/03/微信截图_20240603212354_20240603224414A039.png\",\"url\":\"http://localhost:8080/profile/upload/2024/06/03/微信截图_20240603212354_20240603224414A039.png\"}]",
                    "showLabel": true,
                    "labelWidth": null,
                    "required": true,
                    "span": 24,
                    "showTip": false,
                    "buttonText": "点击上传",
                    "regList": [{"required": true, "message": "拍照上传不能为空"}],
                    "changeTag": true,
                    "fileSize": 2,
                    "sizeUnit": "MB",
                    "document": "https://element.eleme.cn/#/zh-CN/component/upload",
                    "formId": 104,
                    "renderKey": this.model.info.photo
                  },
                  "__slot__": {"list-type": true},
                  "action": "http://localhost:8080/file/upload",
                  "disabled": false,
                  "accept": "image/*",
                  "name": "file",
                  "auto-upload": true,
                  "list-type": "text",
                  "multiple": false,
                  "__vModel__": "photo"
                }, {
                  "__config__": {
                    "label": "备注",
                    "labelWidth": null,
                    "showLabel": true,
                    "tag": "el-input",
                    "tagIcon": "textarea",
                    "required": true,
                    "layout": "colFormItem",
                    "span": 24,
                    "regList": [{"required": true, "message": "请输入备注备注", "trigger": "blur"}],
                    "changeTag": true,
                    "document": "https://element.eleme.cn/#/zh-CN/component/input",
                    "formId": 101,
                    "renderKey": "1011717398850877",
                    "defaultValue": this.model.info.remark
                  },
                  "type": "textarea",
                  "placeholder": "请输入备注备注",
                  "autosize": {"minRows": 4, "maxRows": 4},
                  "style": {"width": "100%"},
                  "maxlength": null,
                  "show-word-limit": false,
                  "readonly": false,
                  "disabled": false,
                  "__vModel__": "remark"
                }]
              }
            }
            startFlow(JSON.stringify(variables), procDefId).then(res=>{
              if (res.code===200){
                this.showToast({
                  type: 'success',
                  title: '提示',
                  message: "提交成功",
                  iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
                }, () => {
                  this.model.info = {
                    type: '',
                    title: '',
                    description: '',
                    photo: '',
                    remark: '',
                  }
                  this.$emit('jumpTo', 2)
                })
              }
            }).catch(errors => {
              uni.$u.toast('提交失败')
            })
          }
        }).catch(errors => {
          uni.$u.toast('提交失败')
        })
      }).catch(errors => {
        uni.$u.toast('校验失败')
      })
    },

    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: config.baseUrl + '/file/upload',
          filePath: url,
          name: 'file',
          header: {
            Authorization: 'Bearer ' + getToken()
          },
          formData: {},
          success: (res) => {
            if (res.statusCode === 200) {
              let parsedData = JSON.parse(res.data);
              if (parsedData && parsedData.url) {
                resolve(parsedData.url); // 假设服务器返回的JSON对象中包含一个名为'url'的属性
              } else {
                reject(new Error('服务器返回的数据不包含文件地址'));
              }
            } else {
              reject(new Error('上传失败，状态码非200'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      })
    },
    getList() {
      uni.showLoading({
        title: '正在加载'
      })
    },
  },
  created() {
  },
}
</script>

<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');

.container {
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  height: 100%;
  font-family: 'Poppins', sans-serif;
  padding: 20rpx;
}
.notice-bar {
  background-color: rgba(255, 255, 255, 0.9);
  color: #333;
  border-radius: 20rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20rpx;
  display: flex;
}


u-navbar {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content {
  margin-top: 80rpx;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  padding: 30rpx;
  margin: 5rpx;
}

.title-container {
  text-align: center;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.grid-container {
  margin-top: 20rpx;
}

.grid-icon {
  color: #3c9cff;
}

.grid-text {
  margin-top: 10rpx;
  font-size: 28rpx;
  color: #333;
}

u-notice-bar {
  background-color: #fff;
  color: #333;
  border-radius: 20rpx;
  margin: 20rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.submit{
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  color: whitesmoke;
  font-weight: bold;
}
</style>
